package com.mojo.linearlist;

/**
 * 线性表-稀疏数组
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/8/30 20:26
 */
public class SparseArray {
    //行
    int row;
    //列
    int line;
    //值
    int value;

    public SparseArray(int row, int line, int value) {
        this.row = row;
        this.line = line;
        this.value = value;
    }

    public static void main(String[] args) {
        //原始二维数组
        int[][] sa = new int[11][11];
        sa[1][2] = 1;
        sa[2][3] = 2;
        sa[4][3] = 11;
        sa[5][4] = 22;
        int sum = 0;
        for (int[] ints : sa) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
                if (anInt != 0) {
                    sum++;
                }
            }
            System.out.println();
        }
        //稀疏数组，第一样存原数组的行数，列数以及元素个数
        //1-初始数组，新数组行数为原数组元素个数加1,列数固定为3
        int[][] sparseArr = new int[sum + 1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;
        //2-赋值
        //记录有几个非0元素
        int count = 0;
        for (int i = 0; i < sa.length; i++) {
            for (int j = 0; j < sa[i].length; j++) {
                //将非0元素赋值
                if (sa[i][j] != 0) {
                    //存储元素所在原数组行数
                    count++;
                    sparseArr[count][0] = i;
                    //存储元素所在原数组列数
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = sa[i][j];
                }
            }
        }
        //2-打印稀疏数组验证
        System.out.println("打印稀疏数组验证~");
        for (int[] ints : sparseArr) {
            System.out.printf("%d\t%d\t%d\t\n", ints[0], ints[1], ints[2]);
        }
        //=======稀疏数组转二维数组=========================
        /*
         *1.获取二维数组的行数，列数
         *2.遍历稀疏数组赋值
         *
         */
        int[][] arr = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
            int row = sparseArr[i][0];
            int line = sparseArr[i][1];
            int value = sparseArr[i][2];
            arr[row][line] = value;
        }
        System.out.println("打印还原的二维数组==>");
        for (int[] ints : arr) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println();
        }
    }
}
